﻿using NHibernate;
using NHibernate.Cfg;
using NHibernate.Connection;
using System.Linq;
using System.Reflection;

namespace NHibernateExample.Business.Core
{
    public class SessionFactory
    {
        static ISessionFactory _sessionFactory;
        public static ISession OpenSession()
        {
            if (_sessionFactory == null)
            {
                // Create configuration instance
                var configuration = new Configuration();

                // Fetch the first connectionProvider, if you have several configure them manually and disable this
                var connectionProvider = Assembly.GetExecutingAssembly().GetTypes().First(x => (typeof(IConnectionProvider)).IsAssignableFrom(x));

                if (connectionProvider != null)
                {
                    // Register the connection probider
                    configuration.SetProperty("connection.provider", connectionProvider.AssemblyQualifiedName);
                }

                configuration.AddAssembly(Assembly.GetCallingAssembly());
                _sessionFactory = configuration.BuildSessionFactory();
            }
            return _sessionFactory.OpenSession();
        }

    }
}
